<?php
/** @var $this ZetaPrints_DistributionMap_Block_Map_Static */

$height = $this->getMapHeight('cart'); // 640;
$width = $this->getMapWidth('cart'); // 480;
$zoom = $this->maphelper()->getInitialZoom();// 12
?>
<script type="text/javascript">
  Event.observe(window, 'load', replaceStaticMap);
  var kmls = null;
  var randid = 1;
  <?php if($kml = $this->renderKml()):?>
  kmls = <?php echo $kml;?>;
    <?php endif;?>
  var options = [];

  function replaceStaticMap() {
    var labels = $$('td > .item-options > dt'); // option label is here
    var regex = new RegExp('\\*\\*\\*kml\\*\\*\\*\s*$', 'i');
    if(!labels || labels.length == 0){
      return;
    }
    labels.each(function(l) {
      var self = $(l);
      var content = self.innerHTML; // original label
      var clean = content.stripTags().strip(); // get label content stripped of tags and white space
      if (regex.test(clean)) {
        var opt = self.next('dd');
        var truncated_full = opt.down('div.truncated_full_value');
        if (truncated_full) {
          var full_value = truncated_full.down('dd').innerHTML.strip();
          try{
            var obj = full_value.evalJSON(true);
            opt.map_nodes = obj;
          }catch(e){
            alert('<?php echo $this->__('JavaScript error. Cannot render map.');?>');
            return;
          }
          opt.innerHTML = '<?php echo $this->__('Loading Google map');?>';
          opt.removeClassName('truncated');
          opt.kml = addKml(kmls, full_value);
        }
        options.push(opt);
        content = content.replace(regex, '');
        self.update(content);
      }
    });
    if(options.length > 0) {
      addMaps();
    }
  }
  function addMaps()
  {
    if(options.length > 0){
      options.each(function(o) {
        var opt = $(o);
        var id = randid++;
        var width = <?php echo (int)$width;?> + 'px';
        var height = <?php echo (int)$height;?> + 'px';
        var config = {};
        config.element = 'map_canvas_' + id;
        config.coords = opt.map_nodes;
        config.zoom = <?php echo $zoom;?>;
        var top = opt.getHeight();
        var map_canvas = '<div class="map-canvas" id="' + config.element + '" style="width: ' + width + '; height: ' + height + '"></div>';
        opt.update(map_canvas);
        var map = new Distromap(config, true);
        if(opt.kml) {
          opt.insert('<br/>' + o.kml);
        }
      });
    }
  }


  <?php if(!$this->isHeadScript()):?>
  replaceStaticMap();
  <?php endif;?>
</script>
